package com.cloudloan.filter;

import com.cloudloan.common.JacksonObjectMapper;
import com.cloudloan.entity.TokenR;
import com.cloudloan.entity.User;
import com.cloudloan.utils.AdministratorThreadLocal;
import com.cloudloan.utils.JwtUtil;
import com.cloudloan.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
//解析token
        String phone="";
        try {
            boolean tokenNotExpired = JwtUtil.isTokenNotExpired(token);
            if (!tokenNotExpired) {
                response.setCharacterEncoding("UTF-8");
                TokenR msg = new TokenR(31104, "token过期请重新登录");
                JacksonObjectMapper jacksonObjectMapper = new JacksonObjectMapper();
                String s = jacksonObjectMapper.writeValueAsString(msg);
                response.getWriter().write(s);
                return;
            }
            Claims claims = JwtUtil.parseJWT(token);
            phone = claims.getSubject();
        } catch (Exception e) {
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("{'status_code':0,'msg':'token解析错误'}");
            return;
        }
        //从redis中获取用户信息
        String redisKey = "login:" + phone;
        User loginSysUser = (User) redisUtils.getCacheObject(redisKey);
        if(Objects.isNull(loginSysUser)){
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("{'status_code':0,'msg':'用户未登录'}");
            return;
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginSysUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //存入ThreadLocal当中
        AdministratorThreadLocal.setAdministrator(loginSysUser);
        //放行
        filterChain.doFilter(request, response);
    }
}
